package org.acme.cluster.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.acme.cluster.po.SysSms;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface SysSmsDao extends BaseMapper<SysSms> {

    @Select("SELECT * FROM sys_sms WHERE server_key = #{serverKey} and status = 0 and retry_count < #{maxRetryCount} ORDER BY create_time ASC limit #{maxBatchSize}")
    public List<SysSms> getSmsListByServerKey(@Param("serverKey") String serverKey, @Param("maxRetryCount") int maxRetryCount, @Param("maxBatchSize") int maxBatchSize);

    @Select("<script>" + "select id from sys_sms where status = 0 and retry_count &lt; #{maxRetryCount} and server_key in ( " + " <foreach collection='serverKeys' separator=',' item='key'>" + " #{key} " + " </foreach> " + " )</script>")
    public List<String> getSmsListByServerKeys(@Param("serverKeys") List<String> serverKeys, @Param("maxRetryCount") int maxRetryCount);

    @Select("<script>" + "select * from sys_sms where server_key = #{serverKey} and status = 0 and retry_count &lt; #{maxRetryCount} and id not in ( " + " <foreach collection='retryIdList' separator=',' item='id'>" + " #{id} " + " </foreach> " + " ) limit #{maxBatchSize}</script>")
    public List<SysSms> getSmsListByServerKeyExceptRetryIdList(@Param("serverKey") String serverKey, @Param("retryIdList") List<String> retryIdList, @Param("maxRetryCount") int maxRetryCount ,@Param("maxBatchSize") int maxBatchSize);

    @Update("<script>" + "UPDATE sys_sms SET server_key = #{newServerKey} where status = 0 and retry_count &lt; #{maxRetryCount} and server_key in ( " + " <foreach collection='oldServerKeys' separator=',' item='key'>" + " #{key} " + " </foreach> " + " )</script>")
    public void updateSmsStatusByServerKeys(@Param("oldServerKeys") List<String> oldServerKeys, @Param("newServerKey") String newServerKey, @Param("maxRetryCount") int maxRetryCount);

    @Update("UPDATE sys_sms SET server_key = #{serverKey} WHERE status = 0 and retry_count < #{maxRetryCount}")
    public void updateALLSmsServerKey(@Param("serverKey") String serverKey, @Param("maxRetryCount") int maxRetryCount);

    @Update("<script>" + "UPDATE sys_sms SET server_key = #{newServerKey} where status = 0 and retry_count &lt; #{maxRetryCount} and id in ( " + " <foreach collection='idList' separator=',' item='id'>" + " #{id} " + " </foreach> " + " )</script>")
    public void updateSmsServerKeyByIdList(@Param("idList") List<String> idList, @Param("newServerKey") String newServerKey, @Param("maxRetryCount") int maxRetryCount);

}
